package com.jy.event.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jy.event.dao.OrderDao;
import com.jy.event.dao.StorePayDao;
import com.jy.event.domain.ElectronicBill;
import com.jy.event.domain.SaoBeiBillReq;
import com.jy.event.domain.Store;
import com.jy.event.domain.StorePay;
import com.jy.event.enums.OrderPayChannel;
import com.jy.event.service.Payservice;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SaoBeiServiceImpl {
    String access_token = "19b4c97dde364fe18371cabdc7d08fa2";
    String prePay_url = "http://test.lcsw.cn:8045/lcsw";

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private StorePayDao storePayDao;

    public ElectronicBill electronicBill(Store store, String date, Date saveDate) throws Exception {
        StorePay storePay = storePayDao.findTop1ByStoreIdAndChannel(store.getId(), OrderPayChannel.SAO_BEI);
        if (null != storePay) {
            SaoBeiBillReq req = new SaoBeiBillReq(storePay.getMchId(), date, date);

            String randStr = UUID.randomUUID().toString();

            JSONObject jsonParam = new JSONObject();
            jsonParam.put("inst_no", "65100020");
            jsonParam.put("trace_no", randStr);
            jsonParam.put("merchant_no", storePay.getMchId());
            jsonParam.put("begin_date", date);
            jsonParam.put("end_date", date);
            String parm = "inst_no=65100020" + "&trace_no=" + randStr + "&merchant_no="
                    + storePay.getMchId() + "&begin_date=" + date + "&end_date="
                    + date + "&access_token=" + access_token;
            String sign = sign(parm, "utf-8");
            jsonParam.put("key_sign", sign);
            String result = tojson(prePay_url + "/merchant/100/withdraw/getsettlement", jsonParam.toJSONString());

            JSONObject jsonObject = JSON.parseObject(result);
            if ("01".equals(jsonObject.getString("result_code"))) {
                JSONArray array = jsonObject.getJSONArray("settle_list");
                for (int i = 0; i < array.size(); i++) {
                    JSONObject jo = array.getJSONObject(i);
                    return new ElectronicBill(store.getId(), storePay.getMchId(), jo.getInteger("settle_amt"), saveDate);
                }
            }
        }

        return null;
    }

    public String tojson(String gateway, String jsonParam) throws Exception {
        String xmlText = "";
        CloseableHttpClient httpclient = HttpClients.custom().build();
        try {

            HttpPost httpPost = new HttpPost(gateway);
            httpPost.addHeader("charset", "UTF-8");
            System.out.println(jsonParam.toString());
            StringEntity stentity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
            stentity.setContentEncoding("UTF-8");
            stentity.setContentType("application/json");
            httpPost.setEntity(stentity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        xmlText = xmlText + text;
                    }
                }

                EntityUtils.consume(entity);
                System.out.println(xmlText);
            } finally {

                response.close();
            }
        } finally {

            httpclient.close();
        }

        return xmlText;
    }

    public static String sign(String text, String input_charset) {
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws
     * @throws
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }
}
